package com.core.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.core.dto.UserDto;
import com.core.mapper.UserMapper;
import com.core.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * create by yongli on 2022-03-23 14:23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDto> implements IUserService {
    @Override
    public void add(UserDto userDto) {
        UserDto userDto1 = getById(userDto.getUsername());
        if (userDto1 == null) {
            save(userDto);
        }
    }

    // 出现异常后回滚
    // 为了保证数据库数据插入的唯一性，还需要在mysql中做唯一性约束
    // 虽然还是可能有on duplicate key on update 等操作，但是还是unique key对结果负责
    // 事物的隔离级别：Cause: com.mysql.cj.jdbc.exceptions.MySQLTransactionRollbackException:
    // 序列化容易死锁，Deadlock found when trying to get lock; try restarting transaction
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED, isolation = Isolation.SERIALIZABLE)
    public void addTransaction(UserDto userDto) {
        UserDto userDto1 = getById(userDto.getUsername());
        if (userDto1 == null) {
            save(userDto);
        }
    }
}
